package com.hulytu.android.sample

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.GridView
import android.widget.TextView
import android.widget.Toast
import com.hulutu.android.samples.R
import com.hulytu.android.adapter.BasicAdapterDelegate
import com.hulytu.android.adapter.listview.BasicViewHolder
import com.hulytu.android.adapter.plugin.BasicDataSetAdapterPlugin
import com.hulytu.android.foundation.app.AppActivity

typealias Adapter = BasicAdapterDelegate<MainActivity.FunctionItem, BasicViewHolder>

class MainActivity : AppActivity(R.layout.activity_main) {

    private val functionAdapter = object : Adapter(BasicDataSetAdapterPlugin()) {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BasicViewHolder {

            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_main_functions, parent, false)

            val holder = BasicViewHolder(view)

            view.setOnClickListener {
                val position = holder.adapterPosition
                get(position).run {
                    onClick.invoke(position, this)
                }
            }

            return holder
        }

        override fun render(holder: BasicViewHolder, data: FunctionItem, position: Int) {

            holder.findViewById<TextView>(R.id.text).run {
                setCompoundDrawablesWithIntrinsicBounds(0, data.icon, 0, 0)
                text = data.name
            }

        }

    }


    override fun doOnCreate(bundle: Bundle?) {
        super.doOnCreate(bundle)

        findViewById<GridView>(R.id.grid_functions)
            .adapter = functionAdapter

        val onClick = { index: Int, item: FunctionItem ->
            Toast.makeText(
                applicationContext,
                "点击了 $index => $item",
                Toast.LENGTH_SHORT
            ).show()
        }

        mutableListOf<FunctionItem>()
            .apply {

                for (i in 0..20) {
                    add(
                        FunctionItem(R.mipmap.ic_launcher_round, "功能 $i", onClick)
                    )
                }

                functionAdapter.setAll(this)
            }


    }


    class FunctionItem(
        val icon: Int = 0,
        val name: String,
        val onClick: (index: Int, item: FunctionItem) -> Unit
    ) {
        override fun toString(): String {
            return "('$name')"
        }
    }
}